import { red, isHttpError, Context } from "../deps.ts";

export default async (ctx: Context, next: () => Promise<void>) => {
  try {
    await next();
  } catch (err) {
    if (isHttpError(err)) {
      ctx.response.status = err.status;
      const { message, status, stack } = err;
      if (ctx.request.accepts("json")) {
        ctx.response.body = { message, status, stack };
        ctx.response.type = "json";
      } else {
        ctx.response.body = `${status} ${message}\n\n${stack ?? ""}`;
        ctx.response.type = "text/plain";
      }
    } else {
      console.log(red(`Unexcepted Error:${err.message}`));
      throw err;
    }
  }
}